package main

import "fmt"

// 观察者
type Observer interface {
	Update(temp float64, humidity float64)
}

// 被观察者
type Subject interface {
	Register(observer Observer)
	Remove(observer Observer)
	Notify()
}

// 具体被观察者（天气）
type WeatherSubject struct {
	observers   []Observer
	temperature float64
	humidity    float64
}

func (ws *WeatherSubject) Register(observer Observer) {
	ws.observers = append(ws.observers, observer)
}

func (ws *WeatherSubject) Remove(observer Observer) {
	for i, o := range ws.observers {
		if o == observer {
			ws.observers = append(ws.observers[:i], ws.observers[i+1:]...)
			break
		}
	}
}

func (ws *WeatherSubject) Notify() {
	for _, o := range ws.observers {
		o.Update(ws.temperature, ws.humidity)
	}
}

func (ws *WeatherSubject) SetMeasurements(temperature, humidity float64) {
	ws.temperature = temperature
	ws.humidity = humidity
	ws.Notify()
}

// 具体观察者（天气站）
type WeatherStation struct {
	name string
}

func (ws *WeatherStation) Update(temperature, humidity float64) {
	fmt.Printf("%s: temperature: %.2f, humidity: %.2f\n", ws.name, temperature, humidity)
}

func main() {
	ws := &WeatherSubject{}
	wst1 := &WeatherStation{name: "wst1"}
	wst2 := &WeatherStation{name: "wst2"}
	ws.Register(wst1)
	ws.Register(wst2)
	ws.SetMeasurements(25.0, 60.0)
}
